package com.jf.identity.task;

import com.jf.identity.dao.vis.DeviceDao;
import com.jf.identity.entity.Device;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 设备信息
 *
 * @author FCG
 */
@Component
public class DeviceTask {
    @Resource
    private DeviceDao deviceDao;
    @Resource
    private MongoTemplate mongoTemplate;
    private Logger logger = LoggerFactory.getLogger(getClass());

//    @Scheduled(fixedRate = 5000)
    public void setDeviceInfos() {
        long start = System.currentTimeMillis();
        Query query = new Query().limit(1000);
        List<Device> devices = mongoTemplate.find(query, Device.class);
        if (devices == null || devices.isEmpty()) {
            return;
        }
        int i = 0;
        try {
            i += insertDeviceInfos(devices);
        } catch (Exception e) {
            logger.error("定时上传设备信息失败", e);
            return;
        }
        for (Device device : devices) {
            mongoTemplate.remove(device);
        }
        long end = System.currentTimeMillis();
        logger.debug("\r\n取出数据:{} 条,\r\n上传设备信息:{} 条,\r\n耗时: {} millis",
                devices.size(), i, (end - start));
    }

    public int insertDeviceInfos(List<Device> devices) {
        for (Device device : devices) {
            String orgCode = device.getExamBaseParam().getOrgCode();
            //设备类型编号
            String deviceTypeId = device.getSBLXM();
            //设备编号
            String deviceNo = device.getSBBH();
            String uid = getDeviceInfoUid(orgCode, deviceTypeId, deviceNo);
            device.setUid(uid);
        }
        int i = deviceDao.insertDeviceInfos(devices);
        return i > devices.size() ? devices.size() : i;
    }


    private String getDeviceInfoUid(String orgCode, String deviceTypeId, String deviceNo) {
        String uid = orgCode + "_" + deviceTypeId + "_" + deviceNo;
        return DigestUtils.md5DigestAsHex(uid.getBytes(Charset.forName("UTF-8")));
    }

}















